package com.tanhua.dubbo.api.impl.mongo;

import com.mongodb.Mongo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.UserUnLike;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import org.apache.dubbo.config.annotation.Service;
import org.omg.PortableInterceptor.ClientRequestInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    private RecommendUserApi recommendUserApi;

    @Autowired
    private FriendApi friendApi;



    //相互喜欢,查询朋友表
    @Override
    public Long queryEachLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long eachLoveCount = mongoTemplate.count(query, Friend.class);
        return eachLoveCount;
    }


    //喜欢
    @Override
    public Long queryLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long loveCount = mongoTemplate.count(query, UserLike.class);
        return loveCount;
    }

    //粉丝
    @Override
    public Long queryFansCount(Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        long fansCount = mongoTemplate.count(query, UserLike.class);
        return fansCount;
    }


    /**
     * 相互喜欢
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult queryEachLoveList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        Long count = mongoTemplate.count(query, Friend.class);
        //pageresult的目标要存储List<Map>
        List<Map<String,Object>> mapList = new ArrayList();
        //遍历朋友列表
        if(friendList!=null){
            for (Friend friend : friendList) {
                Map<String,Object> map = new HashMap<>();
                map.put("userId",friend.getFriendId());
                Long score =recommendUserApi.queryScore(userId,friend.getFriendId());
                map.put("score",score);
                mapList.add(map);
            }
        }

        PageResult pageResult = new PageResult(page,pagesize,count.intValue(),mapList);
        return pageResult;
    }

    /**
     * 喜欢
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult queryLoveList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        Long count = mongoTemplate.count(query, UserLike.class);
        //pageresult的目标要存储List<Map>
        List<Map<String,Object>> mapList = new ArrayList();
        //遍历朋友列表
        if(userLikeList!=null){
            for (UserLike userLike : userLikeList) {
                Map<String,Object> map = new HashMap<>();
                map.put("userId",userLike.getLikeUserId());
                Long score =recommendUserApi.queryScore(userId,userLike.getLikeUserId());
                map.put("score",score);
                mapList.add(map);
            }
        }

        PageResult pageResult = new PageResult(page,pagesize,count.intValue(),mapList);
        return pageResult;
    }

    /**
     * 粉丝
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult queryFansList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        Long count = mongoTemplate.count(query, UserLike.class);
        //pageresult的目标要存储List<Map>
        List<Map<String,Object>> mapList = new ArrayList();
        //遍历朋友列表
        if(userLikeList!=null){
            for (UserLike userLike : userLikeList) {
                Map<String,Object> map = new HashMap<>();
                map.put("userId",userLike.getUserId());
                Long score =recommendUserApi.queryScore(userId,userLike.getLikeUserId());
                map.put("score",score);
                mapList.add(map);
            }
        }

        PageResult pageResult = new PageResult(page,pagesize,count.intValue(),mapList);
        return pageResult;
    }

    /**
     * 谁看过我s
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult queryVisitorsList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(pagesize).skip((page-1)*pagesize);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        Long count = mongoTemplate.count(query, Visitors.class);
        //pageresult的目标要存储List<Map>
        List<Map<String,Object>> mapList = new ArrayList();
        //遍历朋友列表
        if(visitorsList!=null){
            for (Visitors visitors : visitorsList) {
                Map<String,Object> map = new HashMap<>();
                map.put("userId",visitors.getVisitorUserId());
                Long score =recommendUserApi.queryScore(userId,visitors.getVisitorUserId());
                map.put("score",score);
                mapList.add(map);
            }
        }

        PageResult pageResult = new PageResult(page,pagesize,count.intValue(),mapList);
        return pageResult;
    }

    // 删除粉丝记录
    @Override
    public void delete(Long userId, Long fansId) {
        Query query = new Query(Criteria.where("userId").is(fansId).and("likeUserId").is(userId));
        mongoTemplate.remove(query,UserLike.class);
    }

    //探花-喜欢
    @Override
    public void addLikeUser(Long userId, Long likeUserId) {
        //要不要判断这个id是我的粉丝，如果是我粉丝是不是要添加成好友
        Query likeQuery = new Query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId));
        UserLike userLike = mongoTemplate.findOne(likeQuery, UserLike.class);
        if (userLike!=null){
            //存在就跳过，互相添加成好友
            //3. 添加好友
            friendApi.save(userId,likeUserId.intValue());
            //4.删除对方的喜欢的人，并通知对方（未实现）
            Query query = new Query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId));
            mongoTemplate.remove(query,UserLike.class);
        }else {
            userLike = new UserLike();
            userLike.setLikeUserId(likeUserId);
            userLike.setUserId(userId);
            userLike.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(userLike);
        }
    }

    //探花-不喜欢
    @Override
    public void addUnLikeUser(Long userId, Long unLikeUserId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("unLikeUserId").is(unLikeUserId));
        UserUnLike unLike = mongoTemplate.findOne(query, UserUnLike.class);
        if (unLike==null) {
            UserUnLike userUnLike = new UserUnLike();
            userUnLike.setUserId(userId);
            userUnLike.setUnLikeUserId(unLikeUserId);
            userUnLike.setCreated(System.currentTimeMillis());
            mongoTemplate.save(userUnLike);
        }
    }
}
